/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.coinche.server.business;

import java.util.Comparator;
import java.util.List;

import org.jb.coinche.client.business.model.Card;
import org.jb.coinche.client.business.model.Trump;

/**
 * 
 * @author jeremie
 *
 */
public class ColorComparator implements Comparator<Card> {

	final private Trump trump;
	final private Card.Suit askedColor;

	
	/*
	 * 
	 */
	public ColorComparator( Trump trump, Card.Suit askedColor ) {
		this.trump = trump;
		this.askedColor = askedColor;
	}
	
	/*
	 * 
	 */
	public ColorComparator() {
		this.trump = null;
		this.askedColor = null;
	}
	
	/*
	 * 
	 */
	public ColorComparator(Trump trump) {
		this.trump = trump;
		this.askedColor = null;
	}

	/*
	 * 
	 */
	public Trump getTrump() {
		return trump;
	}
	
	/*
	 * 
	 */
	public Card.Suit getAskedColor() {
		return askedColor;
	}
	
	/*
	 * 
	 */
	public boolean isTrump( Card.Suit suit ) {
		return trump != null && (Trump.TOUTAT.equals(trump) || suit.equals(trump.getSuit()));
	}
	
	/*
	 * (non-Javadoc)
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	@Override
	public int compare(Card o1, Card o2) {
		Card.Suit c1 = o1.getSuit();
		Card.Suit c2 = o2.getSuit();
		
		if (c1.equals(c2)) {
			
			List<Card.Rank> values;
			if (isTrump(c1))
				values = Constant.trumpValues;
			else
				values = Constant.defaultValues;
			
			int v1 = values.indexOf( o1.getValue() );
			int v2 = values.indexOf( o2.getValue() );
			
			if (v1 == v2)
				return 0;
			
			if (v1 < v2)
				return -1;
			
			return 1;
		} else {
			
			if (trump != null && c1.equals(trump.getSuit()))
				return -1;
			
			if (trump != null && c2.equals(trump.getSuit()))
				return 1;
			
			if (c1.equals(askedColor))
				return -1;
			
			if (c2.equals(askedColor))
				return 1;
			
			return c1.compareTo(c2);
		}
	}
	

}